package com.github.cakin.shiro.chapter11;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.session.Session;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @className: SerializableUtils
 * @description: Session序列化工具类
 * @date: 2020/5/22
 * @author: cakin
 */
public class SerializableUtils {
    /**
     * 功能描述：序列化session到字符串
     *
     * @param session 以对象形式存在
     * @return String 以字符串形式存在
     * @author cakin
     * @date 2020/5/22
     * @description:
     */
    public static String serialize( Session session ) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(session);
            return Base64.encodeToString(bos.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException("serialize session error", e);
        }
    }

    /**
     * 功能描述：字符串反序列化为Session
     *
     * @param sessionStr 以字符串形式存在
     * @return Session 以对象形式存在
     * @author cakin
     * @date 2020/5/22
     * @description:
     */
    public static Session deserialize( String sessionStr ) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(sessionStr));
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (Session) ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException("deserialize session error", e);
        }
    }
}
